import { useTokenStore, useBusinTokenStore } from "../store";
import pinia from "@/store/piniaInstance";
import { Debounce } from "@/utils/validate";
import {
  LOGIN_STATUS,
  LOGIN_BUSIN_STATUS,
  USER_INFO,
  EXPIRES_TIME,
  STATE_R_KEY,
} from "../config/cache.js";
import Cache from "../utils/cache";
import { isWeixin } from "../utils";
const useTokenStorePina = useTokenStore(pinia);
const useBusinTokenStorePina = useBusinTokenStore(pinia);
export const toLogin = Debounce(_toLogin, 800);
export const weChatLogin = Debounce(_weChatLogin, 800);
// 清除公众号授权token
function _weChatLogin() {
  Cache.clear(LOGIN_BUSIN_STATUS);
  Cache.clear(LOGIN_STATUS);
  let url = "/pages/index/index?reflesh=1";
  if (Cache.get("business_id")) {
    url += `&business_id=${Cache.get("business_id")}`;
  }
  if (Cache.get("urltype")) {
    url += `&urltype=${Cache.get("urltype")}`;
  }
  uni.reLaunch({
    url: url,
  });
}
// 定义不需要检查登录状态的页面路径
const excludeRoutes = [
  "pages/users/login",
  "pages/users/register",
  "pages/users/forget",
];
function _toLogin(push, pathLogin) {
  // uni.showModal({
  //   title:"企业需要登录"
  // })

  Cache.clear(LOGIN_BUSIN_STATUS);
  let path = "/" + prePage();

  // const BASIC_CONFIG = Cache.get("BASIC_CONFIG");
  if (!pathLogin) pathLogin = "/page/users/login";
  Cache.set("login_back_url", path);
  // #ifdef H5
  // 检查当前页面是否在排除列表中
  const isExcludedPage = excludeRoutes.some((route) => path.includes(route));
  if (!isExcludedPage) {
    uni.reLaunch({
      url: "/pages/users/login",
    });
  }
  // #endif

  // #ifdef MP
  let url;
  if (!BASIC_CONFIG.wechat_auth_switch) {
    url = "/pages/users/binding_phone/index?pageType=0";
  } else {
    url = "/pages/users/wechat_login/index";
  }
  uni.navigateTo({
    url,
  });
  // #endif

  // #ifdef APP-PLUS
  uni.navigateTo({
    url: "/pages/users/login/index",
  });
  // #endif
}

function prePage() {
  let pages = getCurrentPages();
  let prePage = pages[pages.length - 1];
  // #ifndef APP-PLUS
  try {
    return prePage.route;
  } catch (error) {}

  // #endif
  // #ifdef APP-PLUS
  return prePage.$page.fullPath;
  // #endif
}
export function checkLogin() {
  let token = Cache.get(LOGIN_STATUS);
  // let token
  let expiresTime = Cache.get(EXPIRES_TIME);
  // let newTime = Math.round(new Date() / 1000);
  if (!token) {
    uni.setStorageSync("authIng", false);
    Cache.clear(LOGIN_STATUS);
    Cache.clear(EXPIRES_TIME);
    Cache.clear(USER_INFO);
    Cache.clear(STATE_R_KEY);
    return false;
  } else {
    // store.commit("UPDATE_LOGIN", token);
    // let userInfo = Cache.get(USER_INFO, true);
    // if (userInfo) {
    //   store.commit("UPDATE_USERINFO", userInfo);
    // }
    return true;
  }
}
